/**
 * 核心技术支持
 * IT渠道网 小程序商城
 * 13873174181 微信同号
 */
import {Cart} from 'cart-model.js';
import {Product} from '../product/product-model';
var cart = new Cart();
var product = new Product();

Page({
    data: {
        loadingHidden: false,
        restUrl: cart.getUrl(),
        showHot: false,
        counts: 0,             //总数
        typeCounts: 0,         //总类
        selectedCounts: 0,     //总数 :已
        selectedTypeCounts: 0, //总类 :已
        //account              //金额 :已
        //cartData             //购物车
        show_cart_edit: false
    },
    /**
     * 获取数据
     */
    onLoad: function(option) {
        this.loadHotList();
    },
    /*
     * 页面渲染 获取/统计
     */
    onShow: function() {
        var cartData = cart.getCartDataFromLocal();
        var calc = this._calcTotalAccountAndCounts(cartData);
        this.setData({
            counts: calc.counts,
            typeCounts: calc.typeCounts,
            selectedCounts: calc.selectedCounts,
            selectedTypeCounts: calc.selectedTypeCounts,
            account: calc.account,
            cartData: cartData,
            loadingHidden: true,
            show_cart_edit: false
        });
        // tabbar
        this.checkTabbar();
    },
    /*
     * 离开时 更新本地缓存
     */
    onHide: function() {
        cart.execSetStorageSync(this.data.cartData);
    },
    /*
     * 计算已选商品
     */
    _calcTotalAccountAndCounts: function(data) {
        var counts1=0,            // 总价格
            counts2=0,            // 总类别
            selectedCounts=0,     // 已选总数量
            selectedTypeCounts=0, // 已选总类别
            account=0,            // 已选总价格
            multiple=100;
        for(var i in data){
            var list = data[i].orderItemList;
            for(var j in list){
                // 选中项, 避免 0.05 + 0.01 = 0.060 000 000 000 000 005 问题，乘以100*100
                if(list[j].selectStatus) {
                    account += list[j].num*multiple * Number(list[j].price)*multiple;
                    selectedCounts += list[j].num;
                    selectedTypeCounts++;
                }
                counts1 += list[j].num;
                counts2++;
            }
        }
        return {
            counts: counts1,
            typeCounts: counts2,
            selectedCounts: selectedCounts,
            selectedTypeCounts: selectedTypeCounts,
            account: (account/(multiple*multiple)).toFixed(2)
        }
    },
    /*
     * 单全选,数量+-,删除,更新购物车数据:切换时,更新缓存数据
     */
    _resetCartData: function() {
      var newData = this._calcTotalAccountAndCounts(this.data.cartData);
      this.setData({
        counts: newData.counts,
        typeCounts: newData.typeCounts,
        selectedCounts: newData.selectedCounts,
        selectedTypeCounts: newData.selectedTypeCounts,
        account: newData.account,
        cartData: this.data.cartData
      });
    },
    /*
     * 调整商品数目 + -
     */
    changeCounts: function(event) {
        var data   = this.data.cartData,
            itemId = cart.getDataSet(event,'id'),   // id
            type   = cart.getDataSet(event,'type'), // cut- add+
            counts = 1,
            multiple = 100;
        // 同步更新缓存
        if(type=='add'){
            //cart.addCounts(itemId); // 更新缓存数据 采用离开时更新
        }else{
            counts = -1;
            //cart.cutCounts(itemId);
        }
        // 更新单品数量
        for(var i in data){
            var list = data[i].orderItemList;
            for(var j in list){
                if(list[j].itemId == itemId){ // 更新数量,小计
                    list[j].num += counts;
                    list[j].totalFee = (list[j].num*multiple*Number(list[j].price)*multiple) / (multiple*multiple);
                }
            }
        }
        this._resetCartData();
    },
    /*
     * 删除商品
     */
    delete: function() {
        var data = this.data.cartData;
        var ids = [];
        // 删除已选单品
        for(let i=data.length-1; i>=0; i--){
            var list = data[i].orderItemList;
            for(let j=list.length-1; j>=0; j--){
                if(list[j].selectStatus){
                    ids.push(list[j].itemId);
                    list.splice(j,1); // 移除单品
                }
            }
            //校验单品为空
            if(list.length == 0){
                data.splice(i,1); // 移除店铺
            }
        };
        this._resetCartData();
        //cart.delete(ids); 采用离开时更新
        this.checkTabbar(); // tabbar
    },
    /*
     * 单选
     */
    toggleSelect: function(event) {
        var id = cart.getDataSet(event,'id'),
            status = cart.getDataSet(event,'status');
        this._getProductIndexById(id);
        this._resetCartData();
    },
    /*
     * 根据商品id
     */
    _getProductIndexById: function(id) {
        var data = this.data.cartData;
        for(var i in data){
            var list = data[i].orderItemList;
            for(var j in list){
                if(list[j].itemId == id){
                    // 单品,状态取反
                    list[j].selectStatus = !list[j].selectStatus;
                    // 校验店铺状态
                    var leng = list.length, yes = 0, no = 0;
                    for(var k in list){
                        if(list[k].selectStatus){ yes ++ }else{ no ++ }
                    }
                    if(leng == yes){
                        data[i].selectStatus = true;
                    }else if(leng == no){
                        data[i].selectStatus = false;
                    }
                }
            }
        }
    },
    /*
     * 全选
     */
    toggleSelectAll: function(event){
        var status = cart.getDataSet(event,'status')=='true',
            data   = this.data.cartData;
        for (var i in data) {
            data[i].selectStatus = !status;
            var list = data[i].orderItemList;
            for (var j in list){
                list[j].selectStatus = !status;
            }
        }
        this._resetCartData();
    },
    /*
     * 店铺全选
     */
    toggleStore: function(event) {
        var sellerId = cart.getDataSet(event,'id'),
            status = cart.getDataSet(event,'status')=='true',
            data   = this.data.cartData;
        for (var i in data) {
            if (data[i].sellerId == sellerId) {
                // 设置状态
                data[i].selectStatus = !status;
                var list = data[i].orderItemList;
                for(var j in list){
                    list[j].selectStatus = !status;
                }
            }
        }
        this._resetCartData();
    },
    /*
     * 切换编辑
     */
    cartEdit: function() {
        this.setData({
            show_cart_edit: true
        })
    },
    /*
     * 切换完成
     */
    cartDone: function() {
        this.setData({
            show_cart_edit: false
        })
    },
    /*
     * 商品详情
     */
    onProductsItemTap: function(event) {
        var id = cart.getDataSet(event, 'id');
        wx.navigateTo({
            url: '../product/product?id=' + id
        })
    },
    /*
     * 提交订单
     */
    submitOrder: function() {
        if (this.data.selectedTypeCounts > 0) {
            wx.navigateTo({
                url: '../order/order?account=' + this.data.account + '&from=cart'
            })
        } else {
            wx.showToast({
                title: '请选择商品',
                icon: 'none',
                duration: 2000
            });
        }
    },
    /**
     * tabbar 
     */
    checkTabbar: function() {
        var num = this.data.typeCounts;
        if (num > 0) {
            wx.setTabBarBadge({
                index: 2,
                text: num.toString()
            })
        } else {
            wx.removeTabBarBadge({
                index: 2
            })
        }
    },
    /**
     * 相关推荐
     */
    loadHotList: function() {
        var that = this;
        product.getHotData(1, (data) => {
            // 截取字符
            data.forEach((item) => {
                item.goodsName = item.goodsName.substring(0, 32);
                item.price = item.price.toFixed(2);
            })
            that.setData({
                hotData: data,
                showHot: true
            })
        })
    }
})